package com.kuanter.kuanterauto.activity;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.City;
import com.kuanter.kuanterauto.main.HomeActivityGroup;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.JsonParser;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;

@SuppressLint("HandlerLeak")
public class CityListActivity extends BaseActivity_NoBar {
	ListView list_city;  //城市列表
	private boolean back = false;  //很多界面调用城市列表,首次进入时不需要返回信息而跳到主界面,从主界面跳转到城市列表时用forResult跳转，这是需要专递参数back=true以做判断
	String city = "";
	TextView current_city_text;
	TextView current_city;
	LinearLayout progress_location;
	ImageButton refresh_city;
	public static int viewOrVisiable = -1;  //-1表示刷新，1表示显示
	
	List<City> cityList;
	LayoutInflater factory;
	
	RelativeLayout re_current_city;
	CityListAdapter adapter;
	
	private boolean closeGPS = true;
	
	TextView btTopLeft_xzpp;
	
//	public static String url = "http://192.168.0.15:8080/service/servlet/";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.citylist);
		factory = getLayoutInflater();
		
		// 欢迎画面后跳转到城市列表
		Intent intent = getIntent();
		if (intent != null) {
			back = intent.getBooleanExtra("back", false);
		}
		
		if(back) {
			closeGPS = false;  //主页面跳转的，按返回不用关闭gps，不用退出程序
		}
		// 从配置中获取city
//		city = SharePrefenceUtil.getCity(this);
		
		initView();
	}

	/**
	 * 初始化activity
	 */
	private void initView() {
		btTopLeft_xzpp = (TextView) findViewById(R.id.btTopLeft_xzpp);
		if(!back) {
			btTopLeft_xzpp.setVisibility(View.GONE);
		}
		
		re_current_city = (RelativeLayout) findViewById(R.id.re_current_city);
		re_current_city.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String currentCity = current_city.getText().toString();
				if(cityList != null) {
					
					for (int i = 0; i < cityList.size(); i++) {
						City mCity = cityList.get(i);
						String cityName = mCity.getCityName();
						if (!currentCity.equals("")) {
							if (cityName.equals(currentCity)) {
								String cityCode = mCity.getCityID();
								String center = mCity.getGpsCoordinate();
								String weaID = mCity.getAreaIdForWeather();
								
								boolean load = true;
								if(SharePrefenceUtil.getCityID(CityListActivity.this).equals(cityCode)) {
									load = false;
								}
								
								SharePrefenceUtil.setCity(CityListActivity.this,
										currentCity);
								SharePrefenceUtil.setCityID(CityListActivity.this,
										cityCode);
								SharePrefenceUtil.setCenter(CityListActivity.this,
										center);
								SharePrefenceUtil.setCityIDForWeather(CityListActivity.this, weaID);
								
								closeGPS = false;
								if (!back) {
									Intent intent = new Intent(
											CityListActivity.this,
											HomeActivityGroup.class);
									startActivity(intent);
								} else {
									Intent intent = new Intent();
									intent.putExtra("load", load);
									setResult(200, intent);
								}
								
								finish();
								
								break;
							}
						}
					}
					
				}
			}
		});
		
		list_city = (ListView) findViewById(R.id.list_city);
		//首先 从本地去，若没有，则用安装包里面的
		try {
			FileInputStream fis = openFileInput("cityList");
			byte[] bytes = new byte[1024];
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while(fis.read(bytes) != -1) {
				baos.write(bytes,0,bytes.length);
			}
			fis.close();
			baos.close();
			String json = new String(baos.toByteArray());
			cityList = JsonParser.getCitys(json);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			cityList = City.getCitys(this);
		} catch (IOException e) {
			e.printStackTrace();
			cityList = City.getCitys(this);
		}
		
		adapter = new CityListAdapter();
		list_city.setAdapter(adapter);
		//然后从服务器取
		
		DataLoader loader = new DataLoader(this);
		loader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.FINDCITY, null, mHandler, "", false);
//		loader.DisplayData(MainConstants.HOST_test + "area/findSubArea", null, mHandler, "", false);
		
		list_city.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View view,
					int i, long l) {
				
				closeGPS = false;
				
				City city = (City) adapterview.getAdapter().getItem(i);
				String str_city_name = city.getCityName();
				String str_city_ID = city.getCityID();
				String str_city_center = city.getGpsCoordinate();
				String str_weatherID = city.getAreaIdForWeather();
				
				boolean load = true;
				if(SharePrefenceUtil.getCityID(CityListActivity.this).equals(str_city_ID)) {
					load = false;
				}
				
				SharePrefenceUtil.setCity(CityListActivity.this, str_city_name);
				SharePrefenceUtil.setCityID(CityListActivity.this, str_city_ID);
				SharePrefenceUtil.setCenter(CityListActivity.this, str_city_center);
				SharePrefenceUtil.setCityIDForWeather(CityListActivity.this, str_weatherID);
				if(!back) {
					Intent intent=new Intent(CityListActivity.this,HomeActivityGroup.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent();
					intent.putExtra("load", load);
					setResult(200, intent);
				}

				finish();
			}
		});
		
		
		current_city_text = (TextView) findViewById(R.id.current_city_text);
		current_city = (TextView) findViewById(R.id.current_city);
		progress_location = (LinearLayout) findViewById(R.id.progress_location);
		refresh_city = (ImageButton) findViewById(R.id.refresh_city);
		refresh_city.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				viewOrVisiable = -1;
				changeViewStatus(false);
				ProApplication application = (ProApplication) getApplication();
				application.startRequest(mHandler);
			}
		});
		
		//进入本页面默认是progress显示，若城市已设置则更变状态
		if(!ProApplication.loc_city.equals("")) {
			city = ProApplication.loc_city;
			viewOrVisiable = 1;
			changeViewStatus(true);
		} else {
			//没有设置城市,调用applicaiotn的请求定位,true表示把请求得到的数据写入配置文件，第二个参数为了区别刷新，因为刷新位置时不需要写如配置
			ProApplication application = (ProApplication) getApplication();
			application.startRequest(mHandler,false);
		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == ProApplication.location_cuccess) {
				city = (String) msg.obj;
				if(cityList != null) {
					for(int i = 0; i < cityList.size(); i++) {
						if(city.equals(cityList.get(i).getCityName())) {
							//TODO  city去掉市
							viewOrVisiable = 1;
							changeViewStatus(true);
							break;
						}
						viewOrVisiable = 1;
						changeViewStatus(false);
					}
				} else {
					viewOrVisiable = 1;
					changeViewStatus(false);
				}
				
			} else if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				cityList = JsonParser.getCitys(json);
				adapter.notifyDataSetChanged();
				try {
					if(StringUtils.isSuccess(json)) {
						try {
							FileOutputStream fos = openFileOutput("cityList", Activity.MODE_PRIVATE);
							fos.write(json.getBytes());
							fos.flush();
							fos.close();
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else if(msg.what == HttpTask.RESULT_ERROR) {
				if(cityList == null) {
					showToast("获取城市列表失败");
				}
			} else if(msg.what == ProApplication.location_fial) {
				viewOrVisiable = 1;
				changeViewStatus(false);
				current_city.setText("定位失败");
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		
		if(!ProApplication.loc_city.equals("")) {
			
		} else {
			refresh_city.performClick();
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if(closeGPS) {
			System.exit(0);
		}
		super.onDestroy();
	}

	//根据状态改变是否显示progressbar
	public void changeViewStatus(boolean click) {
		if(viewOrVisiable == -1) {
			current_city_text.setVisibility(View.GONE);
			current_city.setVisibility(View.GONE);
			current_city.setText("");
			progress_location.setVisibility(View.VISIBLE);
			refresh_city.setVisibility(View.GONE);

			re_current_city.setClickable(click);
			
		} else if(viewOrVisiable == 1) {
			
			current_city_text.setVisibility(View.VISIBLE);
			current_city.setVisibility(View.VISIBLE);
			current_city.setText(city);
			progress_location.setVisibility(View.GONE);
			refresh_city.setVisibility(View.VISIBLE);
			
			re_current_city.setClickable(click);
		}
	}
	
	public void exit(View view) {
		if(back) {
			Intent intent = new Intent();
			intent.putExtra("load", false);
			setResult(200, intent);
		}
		finish();
	}
	
	@Override
	public void onBackPressed() {
		exit(null);
		super.onBackPressed();
	}



	class CityListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return cityList == null ? 0 : cityList.size();
		}

		@Override
		public Object getItem(int i) {
			return cityList.get(i);
		}

		@Override
		public long getItemId(int i) {
			return i;
		}

		@Override
		public View getView(int i, View view, ViewGroup viewgroup) {
			if(view == null) {
				view = factory.inflate(R.layout.citylist_item, null);
			}
			TextView item_cityListName = (TextView) view.findViewById(R.id.item_cityListName);
			TextView item_cityListID = (TextView) view.findViewById(R.id.item_cityListID);
			
			item_cityListName.setText(cityList.get(i).getCityName());
			item_cityListID.setText(cityList.get(i).getCityID());
			
			
			return view;
		}
		
	}
	
	
}
